/*
 * Copyright (c) 2019 DawnFramework. All Rights Reserved.
 * Licensed under the MIT (LICENSE) license.
 */

package org.dawn.common.service.dto;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.dawn.common.core.except.BaseException;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * @author Willard Hu on 2019-04-29.
 */
public class DtoUtils {
    private static final List<String> BASE_FIELDS_MAP = Arrays
            .asList("id", "createdTime", "createdBy", "lastModifiedTime", "lastModifiedBy", "deleted");

    /**
     * 将 Entity 中的属性拷贝到 DTO 中，确保共用属性一致再使用
     */
    public static void copyBaseProperties(BaseDTO<?> dto, Object entity) {
        if (dto == null || entity == null) {
            return;
        }
        try {
            Field src, target;
            for (String fieldName : BASE_FIELDS_MAP) {
                src = FieldUtils.getField(entity.getClass(), fieldName, true);
                target = FieldUtils.getField(dto.getClass(), fieldName, true);
                if (src != null) {
                    target.set(dto, src.get(entity));
                }
            }
        } catch (IllegalAccessException e) {
            throw new BaseException(e);
        }
    }

}
